﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using ST.Buz.Base.Enums;
using Microsoft.AspNetCore.Hosting;

namespace ST.Buz.Service
{
	public partial interface IServiceSysSession
	{
		/// <summary>
		/// 根据请求头部的认证信息刷新会话
		/// </summary>
		UserSession Refresh(string encryptedSessionStr, string userCode);

		/// <summary>
		/// 根据请求头部的认证信息刷新会话
		/// </summary>
		UserSession Refresh(SessionType type, string appID, string openID, string encryptedSessionStr);

		void DeleteByUserID(int userID);
	}

	public partial class ServiceSysSession
	{
		public ServiceSysSession(BuzContext ctx,
				ILogger<ServiceSysSession> log)
		{
			context = ctx;
			logger = log;
		}

		/// <summary>
		/// 根据请求头部的认证信息刷新会话
		/// </summary>
		public UserSession Refresh(string encryptedSessionStr, string userCode)
		{
			throw new NotImplementedException();

			//UserSession userAuthSession = null;
			//try
			//{
			//	if (string.IsNullOrEmpty(userCode))
			//	{
			//		throw new BuzException("用户登录帐号不能为空");
			//	}

			//	DateTime dtNow = DateTime.Now;

			//	var user = context.SysUser.SingleOrDefault(m => m.Code == userCode);
			//	if (user == null)
			//	{
			//		throw new BuzException("未查询到相关帐户信息");
			//	}
			//	var session = context.SysSession.SingleOrDefault(m => m.UserID == user.RowID);
			//	if (session == null)
			//	{
			//		throw new BuzException("未查询到相关会话信息");
			//	}
			//	var userOAuth = context.SysOAuth.SingleOrDefault(m => m.UserID == user.RowID && m.Type == (int)type);
			//	if (userOAuth == null)
			//	{
			//		throw new BuzException("未查询到相关授权信息");
			//	}

			//	try
			//	{
			//		string authSessionStr = EncryptHelper.AESDecrypt(encryptedUserAuthSessionStr, user.Code, session.LastVisit.ToString("yyyyMMdd"));
			//		userAuthSession = Newtonsoft.Json.JsonConvert.DeserializeObject<UserSession>(authSessionStr);
			//	}
			//	catch
			//	{
			//		throw new BuzException("解析验证信息出错");
			//	}
			//	if (userAuthSession == null)
			//	{
			//		throw new BuzException("解析验证信息为空");
			//	}
			//	//todo：可以添加过期时间判断

			//	if (userAuthSession.UserID != user.RowID || userAuthSession.UserCode != user.Code)
			//	{
			//		throw new BuzException("验证信息不一致");
			//	}
			//	#region 更新数据库

			//	#region 更新会话时间
			//	session.LastVisit = dtNow;
			//	#endregion

			//	#region 更新用户信息
			//	user.LastLoginDate = dtNow;
			//	user.LastLoginIP = ip;
			//	#endregion

			//	context.SaveChanges();
			//	#endregion

			//	userAuthSession.OpenID = userOAuth.OpenID;
			//	userAuthSession.SessionID = session.RowID;
			//	userAuthSession.Sessionkey = session.SessionKey;
			//	userAuthSession.SessionType = session.Type;
			//	userAuthSession.State = user.State;
			//	userAuthSession.Timestamp = session.LastVisit.Ticks;
			//	userAuthSession.UnionID = userOAuth.UnionID;
			//	userAuthSession.UserCode = user.Code;
			//	userAuthSession.UserID = user.RowID;
			//	userAuthSession.UserName = user.Name;
			//}
			//catch (BuzException ex)
			//{
			//	throw ex;
			//}
			//catch (DbUpdateException ex)
			//{
			//	logger.LogError(ex.InnerException ?? ex, "刷新授权信息出错");
			//	throw new BuzException("刷新授权信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			//}
			//catch (Exception ex)
			//{
			//	logger.LogError(ex.InnerException ?? ex, "刷新授权信息出错");
			//	throw new BuzException("刷新授权信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			//}

			//return userAuthSession;
		}

		/// <summary>
		/// 根据请求头部的认证信息刷新会话
		/// </summary>
		public UserSession Refresh(SessionType type, string appID, string openID, string encryptedSessionStr)
		{
			throw new NotImplementedException();

			//UserSession userAuthSession = null;
			//try
			//{
			//	if (string.IsNullOrEmpty(userCode))
			//	{
			//		throw new BuzException("用户登录帐号不能为空");
			//	}

			//	DateTime dtNow = DateTime.Now;

			//	var user = context.SysUser.SingleOrDefault(m => m.Code == userCode);
			//	if (user == null)
			//	{
			//		throw new BuzException("未查询到相关帐户信息");
			//	}
			//	var session = context.SysSession.SingleOrDefault(m => m.UserID == user.RowID);
			//	if (session == null)
			//	{
			//		throw new BuzException("未查询到相关会话信息");
			//	}
			//	var userOAuth = context.SysOAuth.SingleOrDefault(m => m.UserID == user.RowID && m.Type == (int)type);
			//	if (userOAuth == null)
			//	{
			//		throw new BuzException("未查询到相关授权信息");
			//	}

			//	try
			//	{
			//		string authSessionStr = EncryptHelper.AESDecrypt(encryptedUserAuthSessionStr, user.Code, session.LastVisit.ToString("yyyyMMdd"));
			//		userAuthSession = Newtonsoft.Json.JsonConvert.DeserializeObject<UserSession>(authSessionStr);
			//	}
			//	catch
			//	{
			//		throw new BuzException("解析验证信息出错");
			//	}
			//	if (userAuthSession == null)
			//	{
			//		throw new BuzException("解析验证信息为空");
			//	}
			//	//todo：可以添加过期时间判断

			//	if (userAuthSession.UserID != user.RowID || userAuthSession.UserCode != user.Code)
			//	{
			//		throw new BuzException("验证信息不一致");
			//	}
			//	#region 更新数据库

			//	#region 更新会话时间
			//	session.LastVisit = dtNow;
			//	#endregion

			//	#region 更新用户信息
			//	user.LastLoginDate = dtNow;
			//	user.LastLoginIP = ip;
			//	#endregion

			//	context.SaveChanges();
			//	#endregion

			//	userAuthSession.OpenID = userOAuth.OpenID;
			//	userAuthSession.SessionID = session.RowID;
			//	userAuthSession.Sessionkey = session.SessionKey;
			//	userAuthSession.SessionType = session.Type;
			//	userAuthSession.State = user.State;
			//	userAuthSession.Timestamp = session.LastVisit.Ticks;
			//	userAuthSession.UnionID = userOAuth.UnionID;
			//	userAuthSession.UserCode = user.Code;
			//	userAuthSession.UserID = user.RowID;
			//	userAuthSession.UserName = user.Name;
			//}
			//catch (BuzException ex)
			//{
			//	throw ex;
			//}
			//catch (DbUpdateException ex)
			//{
			//	logger.LogError(ex.InnerException ?? ex, "刷新授权信息出错");
			//	throw new BuzException("刷新授权信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			//}
			//catch (Exception ex)
			//{
			//	logger.LogError(ex.InnerException ?? ex, "刷新授权信息出错");
			//	throw new BuzException("刷新授权信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			//}

			//return userAuthSession;
		}

		public void DeleteByUserID(int userID)
		{
			context.Database.ExecuteSqlRaw("DELETE FROM Sys_Session WHERE UserID={0}", userID);
		}
	}
}